package org.daochong.fastdev.funcs;

import java.sql.SQLException;

import org.daochong.fastdev.Context;
import org.daochong.fastdev.Function;
import org.daochong.fastdev.OperationId;
import org.daochong.fastdev.util.FastDevUtils;
import org.daochong.lang.BeanUtil;
import org.daochong.lang.Page;
import org.daochong.lang.StringUtils;

public class PageFunction implements Function {

	public boolean is(String id) {
		return FastDevUtils.operNumber("page", id) || FastDevUtils.operEntity("page", id);
	}

	public void exec(String key, String prop, Context context)  throws SQLException{
		if (!is(key))
			throw new RuntimeException("Function  not match [" + key + "]");
		prop = BeanUtil.formatString(prop, context);
		Page page = new Page();
		BeanUtil.pushBean(context.getParameters(), page);
		if (FastDevUtils.operNumber("page", key)) {
			if (StringUtils.isEmpty(prop))
				return;
			for (OperationId oid : FastDevUtils.operationIds(prop)) {
				Object obj = context.getJdbcOperations().page(page, oid.getId(), context.getParameters());
				context.add(oid, obj);
			}
		} else {
			if (StringUtils.isEmpty(prop)) {
				String entityType = key.substring(5);
				Class<?> clazz = context.getClassMappingFactory().getEntity(entityType);
				Object obj = context.getJpaOperations().page(BeanUtil.pushBean(context.getParameters(), Page.class), clazz);
				OperationId oid = new OperationId();
				oid.setId(entityType);
				context.add(oid, obj);
			} else {
				OperationId oid = FastDevUtils.operationId(prop);
				Class<?> clazz = context.getClassMappingFactory().getEntity(key.substring(5));
				Object obj = context.getJpaOperations().pageBySql(page, oid.getId(), clazz, context.getParameters());
				context.add(oid, obj);
			}
		}
	}

}
